package com.niren.commonmodule.util;


import com.niren.commonmodule.basic.EUseSystem;
import com.niren.commonmodule.util.supportclass.UserTokenInfo;
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.UUID;

public class JwtTokenUtils {

    private final static Logger logger = LoggerFactory.getLogger(JwtTokenUtils.class);

    //public static long expiry = 60*60*24*7;//目前为一周
    public static long pcExpiry = 60*60*2;//PC端有效期为2小时
    public static long weChatExpiry = 60*60*24*30;//微信公众号及小程序有效效为30天
    /**
     * 有效期
     */
    private static long timeBase = 1000;//单位为毫秒
    /**
     * 加密用的密码?
     */
    private static String signature = "niRen-microservice";

    private static final String USER_ID = "userId";
    private static final String USER_NAME = "userName";

    public static String createToken(UserTokenInfo info, int useSystem) {
        JwtBuilder jwtBuilder = Jwts.builder();
        long time = 0;
        if(EUseSystem.EUseSystem2Int(EUseSystem.PC) == useSystem)
            time = timeBase * pcExpiry;
        else
            time = timeBase * weChatExpiry;
        String jwtToken = jwtBuilder
                //header
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                //payload
                .claim(USER_ID,info.getUserId()+"")
                .claim(USER_NAME,info.getUserName())
                .claim("role","sys-user")
                .setSubject("admin-test")
                .setExpiration(new Date(System.currentTimeMillis() + time))
                .setId(UUID.randomUUID().toString())
                //signature
                .signWith(SignatureAlgorithm.HS256,signature)
                //调用拼接接口
                .compact();
        //logger.info("<token:" + jwtToken + ">,<token_hex:" + Convert.bytes2HexString(jwtToken.getBytes()) + ">");
        return jwtToken;
    }

    public static UserTokenInfo parse(String token){
        JwtParser jwtParser = Jwts.parser();
        try{
            Jws<Claims> claimsJws = jwtParser.setSigningKey(signature).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return new UserTokenInfo(
                    claims.get(USER_ID).toString(),
                    claims.get(USER_NAME).toString(),
                    claims.getExpiration()
            );
        }catch (Exception e) {
            return null;
        }
    }

}
